﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Net;
using System.Diagnostics;

namespace SPWarmup
{
    public class WarmUpTimerJob : SPJobDefinition
    {
        protected override bool HasAdditionalUpdateAccess()
        {
            return true;
        }

        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                Trace.TraceInformation("Warming up Sharepoint web applications / application pools..");

                ITopologyService topologyService = new TopologyService();
                var webApplications = topologyService.GetContentApplications();

                Trace.TraceInformation("Found {0} Web Applications", webApplications.Count);

                foreach (var webApp in webApplications)
                {
                    try
                    {
                        Console.Write("Warming up {0}", webApp.Name);
                        webApp.WarmUp();
                        Trace.TraceInformation("- OK -");
                    }
                    catch (WebException ex)
                    {
                        Trace.TraceError("  Error warming up {0}: {1}", webApp.Name, ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("  Error warming up {0}: {1}", webApp.Name, ex.Message);
                    }

                }
            }
            finally
            {
                //nothing todo yet
            }
        }

    }
}
